//
//  PVDDetailPanelNumberView.swift
//  ezyform
//
//  Created by MoennigQ on 2/5/18.
//  Copyright © 2018 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import SnapKit
import RxCocoa
import RxSwift
import RxGesture

class PVDPanelsListView: PanleInverterListBaseView {
    fileprivate lazy var disposeBag = DisposeBag()
    var modelsDataObserver: BehaviorRelay<[InstallationDetailSystemDetailForPanelModel]> = BehaviorRelay(value: [])

    //table view
    let modelsTableView: UITableView = TableView()
    var modelsTableViewHeightConstraint: Constraint?
    let panelsTableView: UITableView = TableView()
    //spv top view
    let scannedCntLabel = BaseLabel()
    //
    let spvInfoView = View()
    let invalidCntLabel = OptionTypeLabel("Invalid: 0",leftRightPadding: 14, topBottomPadding: 8)
    let verifiedCntLabel = OptionTypeLabel("Verified: 0",leftRightPadding: 14, topBottomPadding: 8)
    var resultCheckBtn = UIButton()
    //
    var filterPanelStatus: PanelNumberSPVStatus = .all
    override func setUpView() {
        super.setUpView()
        modelsTableView.drawCorner(byRoundingCorners: [.topLeft,.topRight],radii: 16)
        modelsTableView.clipsToBounds = true
        modelsTableView.backgroundColor = UIColor(hexStr: Constant.TransparentColorHexStr)
        modelsTableView.register(JobDetailPanelTableViewCell.self, forCellReuseIdentifier: JobDetailPanelTableViewCell.reuseCellIdentifier)
        modelsTableView.isScrollEnabled = false
        modelsTableView.showsVerticalScrollIndicator = false
        self.contentBackView.addSubview(modelsTableView)
        modelsTableView.snp.makeConstraints { make in
            make.top.equalTo(20)
            make.left.equalTo(Constant.AllOutMargin)
            make.right.equalTo(-Constant.AllOutMargin)
            self.modelsTableViewHeightConstraint = make.height.equalTo(0).constraint
        }
        //serperate view
        let serperateView = View(hexStr: "#F5F5F5FF")
        self.contentBackView.addSubview(serperateView)
        serperateView.snp.makeConstraints { make in
            make.top.equalTo(modelsTableView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(4)
        }
        
        //title label
        let panelSerialLabel = ContentLabel(R.font.interMedium(size: 14),hexStr: "#292D3299")
        panelSerialLabel.text = R.string.localizable.serialNumbers("Panel")
        self.contentBackView.addSubview(panelSerialLabel)
        panelSerialLabel.snp.makeConstraints { (make) in
            make.left.equalTo(16)
            make.top.equalTo(serperateView.snp.bottom).offset(20)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //
        self.contentBackView.addSubview(scannedCntLabel)
        scannedCntLabel.snp.makeConstraints { (make) in
            make.left.equalTo(panelSerialLabel.snp.right).offset(12)
            make.height.width.greaterThanOrEqualTo(0)
            make.centerY.equalTo(panelSerialLabel)
        }
        //spv info View
        self.contentBackView.addSubview(spvInfoView)
        spvInfoView.snp.makeConstraints { make in
            make.top.equalTo(scannedCntLabel.snp.bottom)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.greaterThanOrEqualTo(35)
        }
        //
        spvInfoView.addSubview(invalidCntLabel)
        invalidCntLabel.snp.makeConstraints { (make) in
            make.left.top.bottom.equalToSuperview()
            make.width.greaterThanOrEqualTo(0)
        }
        //
        spvInfoView.addSubview(verifiedCntLabel)
        verifiedCntLabel.snp.makeConstraints { (make) in
            make.left.equalTo(invalidCntLabel.snp.right).offset(6)
            make.top.bottom.equalToSuperview()
            make.width.greaterThanOrEqualTo(0)
        }
        resultCheckBtn.setImage(R.image.installation_detail_panelnumber_resultcheck(), for: UIControl.State.normal)
        spvInfoView.addSubview(resultCheckBtn)
        resultCheckBtn.snp.makeConstraints { (make) in
            make.top.bottom.right.equalToSuperview()
            make.width.equalTo(113)
        }
        //
        panelsTableView.showsVerticalScrollIndicator = false
        self.contentBackView.addSubview(panelsTableView)
        panelsTableView.snp.makeConstraints { make in
            make.top.equalTo(spvInfoView.snp.bottom).offset(10)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview()
        }
        //设置cell信息，绑定数据源
        modelsDataObserver.bind(to: modelsTableView.rx.items(cellIdentifier: JobDetailPanelTableViewCell.reuseCellIdentifier,cellType: JobDetailPanelTableViewCell.self)){(row, model, cell) in
            cell.setData(model,index: row)
        }.disposed(by: self.disposeBag)
        //观察数据变化，刷新数据
        modelsDataObserver.asObservable().subscribe(onNext: {[weak self] (list) in
            self?.modelsTableView.reloadData()
        }).disposed(by: disposeBag)
        //MARK: - 监听Contensize是获取Tableview 高度最准确的方法
        modelsTableView.rx.observe(CGSize.self,"contentSize").subscribe {[weak self] (size) in
            guard let contentSize = size else {return}
            self?.modelsTableViewHeightConstraint?.update(offset: contentSize.height)
        }.disposed(by: self.disposeBag)
        //
        //注册cell
        panelsTableView.register(InstallationDetailTabPanelNumberCell.self, forCellReuseIdentifier: InstallationDetailTabPanelNumberCell.reuseCellIdentifier)
        //数据绑定
        JobDetailModelHelper.shared.pvd_serial_numbers.map({ list in
            list.filter({
                if self.filterPanelStatus == .all{
                    return true
                }else {
                    return $0.spv_status.lowercased() == self.filterPanelStatus.rawValue
                }
            })
        }).bind(to: panelsTableView.rx.items(cellIdentifier: InstallationDetailTabPanelNumberCell.reuseCellIdentifier,cellType: InstallationDetailTabPanelNumberCell.self)){(row, model, cell) in
            cell.setData(model)
        }.disposed(by: self.disposeBag)
        //绑定pvd_serial_number的数量显示
        JobDetailModelHelper.shared.pvd_serial_numbers.subscribe { panelList in
            let neededNumberCnt = JobDetailModelHelper.shared.jobDetailModel.system_detail.panel_plant_count
            let scannedNumberCnt = "\(JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers.count)"
            let combineStr = scannedNumberCnt + "/\(neededNumberCnt)"
            
            let attrString = NSMutableAttributedString(string: combineStr )
            let attr1: [NSMutableAttributedString.Key: Any] = [.foregroundColor: UIColor(hexStr: "#379657")]
            let attr2: [NSMutableAttributedString.Key: Any] = [.foregroundColor: UIColor(hexStr: "#292D32")]
            
            attrString.addAttributes(attr1, range: NSRange(location: 0, length: scannedNumberCnt.count))
            attrString.addAttributes(attr2, range: NSRange(location: scannedNumberCnt.count, length: combineStr.count - scannedNumberCnt.count))
            self.scannedCntLabel.attributedText = attrString
            self.scannedCntLabel.setFont(R.font.sfProTextMedium(size: 13))
            //设置invalid cnt，verified cnt
            let invalidCnt = JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers.filter({$0.spv_status.lowercased() == PanelNumberSPVStatus.invalid.rawValue}).count
            let verifiedCnt = JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers.filter({$0.spv_status.lowercased() == PanelNumberSPVStatus.verified.rawValue}).count
            self.invalidCntLabel.text = "Invalid: \(invalidCnt)"
            self.verifiedCntLabel.text = "Verified: \(verifiedCnt)"
        }.disposed(by: self.disposeBag)
        //选择invalid，筛选invalid数据
        invalidCntLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else {return}
            //
            if strongSelf.invalidCntLabel.tag == 0 {//筛选，取消筛选
                strongSelf.verifiedCntLabel.setUnSelect()//取消verified的筛选
                strongSelf.invalidCntLabel.setSelect()
                strongSelf.filterPanelStatus = .invalid
            }else{
                strongSelf.invalidCntLabel.setUnSelect()
                strongSelf.filterPanelStatus = .all
            }
            JobDetailModelHelper.shared.pvd_serial_numbers.onNext(JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers)
        }).disposed(by: self.disposeBag)
        //选择invalid，筛选invalid数据
        verifiedCntLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else {return}
            //
            if strongSelf.verifiedCntLabel.tag == 0 {//筛选，取消筛选
                strongSelf.invalidCntLabel.setUnSelect()//取消verified的筛选
                strongSelf.verifiedCntLabel.setSelect()
                strongSelf.filterPanelStatus = .verified
            }else{
                strongSelf.verifiedCntLabel.setUnSelect()
                strongSelf.filterPanelStatus = .all
            }
            JobDetailModelHelper.shared.pvd_serial_numbers.onNext(JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers)
            
        }).disposed(by: self.disposeBag)
    }
    func updateUIByJobStatus(){
        
        let jobStatus: String = JobDetailModelHelper.shared.jobDetailModel.job_status
        let spvCheck =  JobDetailModelHelper.shared.jobDetailModel.spv_check//是否开启了spv
        let spvInstalled =  JobDetailModelHelper.shared.jobDetailModel.spv_installed
        //job finish或者panel installed或者当前用户不是installer
        if jobStatus == PVDJobStatusValue.installed.rawValue || (spvInstalled && spvCheck) || !JobDetailModelHelper.shared.jobDetailModel.isInstallerFlag{
            self.hideBottomBtns(true)
        }else{
            self.hideBottomBtns(false)
        }
        
    }
    func setPanelNumberSPVInfo(){
        //开启了SPV验证，
        if JobDetailModelHelper.shared.jobDetailModel.spv_check {//开启了spv
            //panel number 已经验证通过
            if JobDetailModelHelper.shared.jobDetailModel.spv_installed{//panel installed了
                self.showSPVInfoView(false)
            }else{
                if JobDetailModelHelper.shared.jobDetailModel.isInstallerFlag {//是Installer才显示
                    self.showSPVInfoView(true)
                }else{
                    self.showSPVInfoView(false)
                }
            }
        }else{//没开启spv，隐藏spv 的btns
            self.showSPVInfoView(false)
        }
    }
    //MARK: - showFlag = true表示显示，false表示不显示
    private func showSPVInfoView(_ showFlag: Bool){
        if showFlag {
            spvInfoView.isHidden = false
            spvInfoView.snp.remakeConstraints { make in
                make.top.equalTo(scannedCntLabel.snp.bottom).offset(9)
                make.left.equalTo(16)
                make.right.equalTo(-16)
                make.height.equalTo(35)
            }
        }else{
            spvInfoView.isHidden = true
            spvInfoView.snp.remakeConstraints { make in
                make.bottom.equalTo(scannedCntLabel.snp.bottom)
                make.left.equalTo(16)
                make.right.equalTo(-16)
                make.height.equalTo(0)
            }
        }
    }
}
